package com.example.fengshoutong;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;

import com.example.fengshoutong.greendao.DaoMaster;
import com.example.fengshoutong.greendao.DaoSession;

public class MainApplication extends Application {
    private static final String TAG = "MainApplication";
    private static MainApplication instance;
    private DaoSession goodDaoSession;
    private DaoSession userDaoSession;
    private DaoSession articleDaoSession;

    /**
     * 单例模式
     *
     * @return
     */
    public static MainApplication getInstance() {
        if (instance == null)
            instance = new MainApplication();
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initGreenDao();
    }

    /**
     * 初始化GreenDao,直接在Application中进行初始化操作
     */
    private void initGreenDao() {
        // 创建商品数据库
        DaoMaster.DevOpenHelper goodHelper = new DaoMaster.DevOpenHelper(this, "good.db");
        SQLiteDatabase goodDb = goodHelper.getWritableDatabase();
        DaoMaster goodDaoMaster = new DaoMaster(goodDb);
        goodDaoSession = goodDaoMaster.newSession();

        // 创建用户数据库
        DaoMaster.DevOpenHelper userHelper = new DaoMaster.DevOpenHelper(this, "user.db");
        SQLiteDatabase userDb = userHelper.getWritableDatabase();
        DaoMaster userDaoMaster = new DaoMaster(userDb);
        userDaoSession = userDaoMaster.newSession();

        // 创建文章数据库
        DaoMaster.DevOpenHelper articleHelper = new DaoMaster.DevOpenHelper(this, "article.db");
        SQLiteDatabase articleDb = articleHelper.getWritableDatabase();
        DaoMaster articleDaoMaster = new DaoMaster(articleDb);
        articleDaoSession = articleDaoMaster.newSession();
    }

    /**
     * 获取商品数据库
     *
     * @return
     */
    public DaoSession getGoodDaoSession() {
        return goodDaoSession;
    }

    /**
     * 获取用户数据库
     *
     * @return
     */
    public DaoSession getUserDaoSession() {
        return userDaoSession;
    }

    /**
     * 获取文章数据库
     *
     * @return
     */
    public DaoSession getArticleDaoSession() {
        return articleDaoSession;
    }
}
